<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询用户名" v-model="username"></el-input>
      <el-input style="width: 200px; margin: 0 5px" placeholder="查询姓名"  v-model="name"></el-input>
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="info" plain @click="exportData">批量导出</el-button>
      <el-upload :action="importAction" :headers="uploadHeaders" :on-success="handleImport" style="display: inline-block; margin-left: 10px" :show-file-list="false">
        <el-button type="primary" plain>批量导入</el-button>
      </el-upload>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="250" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column label="状态" width="350">
            <template #default="{ row }">
            <el-tag
                :type="row.status === '0' ? 'success' : 'danger'"
                size="mini"
                effect="plain"
            >
                {{ row.status === '0' ? '正常' : '停用' }}
            </el-tag>
            </template>
       </el-table-column>
       <el-table-column label="管理员" width="100">
            <template #default="{ row }">
            <el-tag
                :type="row.isAdmin === '1' ? 'warning' : 'info'"
                size="mini"
                effect="plain"
            >
                {{ row.isAdmin === '1' ? '是' : '否' }}
            </el-tag>
            </template>
        </el-table-column>
    
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="租户信息" :visible.sync="fromVisible" width="40%">
      <el-form :model="form" label-width="100px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :disabled="!!form.id"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员权限" prop="isAdmin">
          <el-radio-group v-model="form.isAdmin">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="修改后密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入修改后密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="form.password && form.password.length > 0">
          <el-input v-model="form.confirmPassword" placeholder="请再次输入密码" show-password></el-input>
        </el-form-item>
        <!-- Resource Quota Fields -->
        <el-form-item label="CPU 限制" prop="resourceQuota.cpuLimit">
          <el-input v-model="form.resourceQuota.cpuLimit" placeholder="请输入 CPU 限制 (e.g., 1000m)"></el-input>
        </el-form-item>
        <el-form-item label="CPU 请求" prop="resourceQuota.cpuRequest">
          <el-input v-model="form.resourceQuota.cpuRequest" placeholder="请输入 CPU 请求 (e.g., 500m)"></el-input>
        </el-form-item>
        <el-form-item label="内存限制" prop="resourceQuota.memoryLimit">
          <el-input v-model="form.resourceQuota.memoryLimit" placeholder="请输入内存限制 (e.g., 2Gi)"></el-input>
        </el-form-item>
        <el-form-item label="内存请求" prop="resourceQuota.memoryRequest">
          <el-input v-model="form.resourceQuota.memoryRequest" placeholder="请输入内存请求 (e.g., 1Gi)"></el-input>
        </el-form-item>
        <el-form-item label="GPU 限制" prop="resourceQuota.gpuLimit">
          <el-input v-model="form.resourceQuota.gpuLimit" placeholder="请输入 GPU 限制 (e.g., 1)"></el-input>
        </el-form-item>
        <el-form-item label="GPU 内存" prop="resourceQuota.gpuMemory">
          <el-input v-model="form.resourceQuota.gpuMemory" placeholder="请输入 GPU 内存 (e.g., 8Gi)"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTenantList, deleteTenant, batchDeleteTenants, updateTenant, addTenant, exportTenants, getImportUrl } from '@/api/tenant/tenant'

export default {
  name: "Tenant",
  data() {
    return {
      tableData: [],  // 当前页显示的数据
      allTableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      username: '',
      name: '',
      total: 0,
      fromVisible: false,
      form: {
        resourceQuota: {
          cpuLimit: '',
          cpuRequest: '',
          memoryLimit: '',
          memoryRequest: '',
          gpuLimit: '',
          gpuMemory: ''
        }
      },
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' },
        ],
        isAdmin: [
          { required: true, message: '请选择管理员权限', trigger: 'change' },
        ],
        password: [
          { required: false, message: '请输入密码', trigger: 'blur' },
        ],
        confirmPassword: [
          { required: false, message: '请确认密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ],
      },
      ids: []
    }
  },
  computed: {
  uploadHeaders() {
    const user = JSON.parse(localStorage.getItem('honey-user') || '{}');
    return { 
      'Authorization': 'Bearer ' + user.token,
      'token': user.token  // 同时保留原来的格式
    }
  },
  uploadAction() {
    return this.$baseUrl + '/file/upload'
  },
  importAction() {
    return this.$baseUrl + getImportUrl()
  }
},
  created() {
    this.load()
  },
  methods: {
    handleImport(res, file, fileList) {
      if (res.code === '200' || res.code === 200) {
        this.$message.success("操作成功")
        this.load(1)
      } else {
        this.$message.error(res.msg)
      }
    },
    exportData() {
      const exportUrl = exportTenants(this.ids, this.user.token)
      window.open(exportUrl)
    },
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        batchDeleteTenants(this.ids).then(res => {
          if (res.code === '200' || res.code === 200) {
            this.$message.success('操作成功')
            this.load(1)
            this.fromVisible = false
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {})
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    del(id) {
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(response => {
        deleteTenant(id).then(res => {
          if (res.code === '200' || res.code === 200) {
            this.$message.success('操作成功')
            this.load(1)
            this.fromVisible = false
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {})
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      // 确保 resourceQuota 字段存在
      if (!this.form.resourceQuota) {
        this.form.resourceQuota = {
          cpuLimit: '',
          cpuRequest: '',
          memoryLimit: '',
          memoryRequest: '',
          gpuLimit: '',
          gpuMemory: ''
        }
      }
      this.fromVisible = true
    },
    handleAdd() {
      this.form = {
        role: '用户',
        resourceQuota: {
          cpuLimit: '',
          cpuRequest: '',
          memoryLimit: '',
          memoryRequest: '',
          gpuLimit: '',
          gpuMemory: ''
        }
      }
      this.fromVisible = true
    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 创建一个副本，避免修改原始数据
          const formData = JSON.parse(JSON.stringify(this.form));
          
          // 如果没有输入新密码，则删除密码相关字段
          if (!formData.password || formData.password.length === 0) {
            delete formData.password;
          } else {
            // 如果输入了新密码，但确认密码为空或不匹配，则提示错误
            if (!formData.confirmPassword || formData.confirmPassword !== formData.password) {
              this.$message.error('两次输入的密码不一致');
              return;
            }
            // 删除确认密码字段，因为后端不需要
            delete formData.confirmPassword;
          }
          
          if (this.form.id) {
            updateTenant(this.form.id, formData).then(res => {
              if (res.code === '200' || res.code === 200) {
                this.$message({
                  message: '更新成功',
                  type: 'success',
                  showClose: false
                })
                this.load(1)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            addTenant(formData).then(res => {
              console.log('新增租户响应:', res); // 调试信息
              if (res.code === '200' || res.code === 200) {
                this.$message({
                  message: '新增成功',
                  type: 'success',
                  showClose: false,
                  duration: 3000 // 3秒后自动关闭
                })
                this.fromVisible = false
                this.load(1)
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    reset() {
      this.name = ''
      this.username = ''
      this.pageNum = 1
      this.load()
    },
    load(pageNum) {
        if (pageNum) this.pageNum = pageNum
         
        // 构造查询参数（暂时不传递分页参数，因为后端似乎不支持）
        const params = {
            // 移除分页参数，因为后端目前不支持
            username: this.username,
            name: this.name
        }
        
        getTenantList(params).then(res => {
        if (res.code === 200 || res.code === '200') {
            // 保存所有数据
            this.allTableData = res.users || []
            // 更新总记录数
            this.total = this.allTableData.length
            // 根据当前页码和页面大小计算显示的数据
            const start = (this.pageNum - 1) * this.pageSize
            const end = start + this.pageSize
            this.tableData = this.allTableData.slice(start, end)
            
            this.$message({
              message: '数据加载成功',
              type: 'success',
              showClose: false
            })
        } else {
            this.$message({
              message: res.msg || '获取数据失败',
              type: 'error',
              showClose: false
            })
        }
        })
        .catch(error => {
        
        this.$message({
          message: '请求失败: ' + (error.message || '未知错误'),
          type: 'error',
          showClose: false
        })
        })
},
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      // 计算当前页数据
      const start = (this.pageNum - 1) * this.pageSize
      const end = start + this.pageSize
      this.tableData = this.allTableData.slice(start, end)
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1 // 页大小改变时回到第一页
      // 重新计算当前页数据
      const start = (this.pageNum - 1) * this.pageSize
      const end = start + this.pageSize
      this.tableData = this.allTableData.slice(start, end)
    },
    handleAvatarSuccess(response, file, fileList) {
      this.form.avatar = response.data
    },
    validatePassword(rule, value, callback) {
      if (this.form.password && value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
  }
}
</script>

<style scoped>
</style>
